<template>
  <view class="filter-container">
    <!-- 一级筛选菜单 -->
    <scroll-view class="primary-filter" scroll-x="true" show-scrollbar="false">
      <view 
        v-for="(item, index) in primaryFilters" 
        :key="index"
        class="primary-item"
        :class="{ active: activePrimary === index }"
        @click="selectPrimary(index)"
      >
        <text>{{ item.name }}</text>
        <u-icon 
          v-if="item.icon" 
          :name="item.icon" 
          size="16" 
          :color="activePrimary === index ? '#2979ff' : '#999'"
        ></u-icon>
      </view>
    </scroll-view>
    
    <!-- 二级筛选菜单（弹出层） -->
    <u-popup 
      :show="showSecondary" 
      mode="bottom" 
      round="16"
      @close="closeSecondary"
    >
      <view class="secondary-container">
        <!-- 标题栏 -->
        <view class="secondary-header">
          <text class="title">{{ currentPrimary.name }}</text>
          <u-icon name="close" size="22" @click="closeSecondary"></u-icon>
        </view>
        
        <!-- 二级筛选内容 -->
        <scroll-view scroll-y="true" class="secondary-content">
          <!-- 类型1：单选列表 -->
          <template v-if="currentPrimary.type === 'radio'">
            <view 
              v-for="(option, idx) in currentPrimary.options" 
              :key="idx"
              class="option-item"
              :class="{ selected: selectedOption === option.value }"
              @click="selectOption(option.value)"
            >
              <text>{{ option.label }}</text>
              <u-icon 
                v-if="selectedOption === option.value" 
                name="checkbox-mark" 
                color="#2979ff" 
                size="20"
              ></u-icon>
            </view>
          </template>
          
          <!-- 类型2：多选列表 -->
          <template v-else-if="currentPrimary.type === 'checkbox'">
            <view 
              v-for="(option, idx) in currentPrimary.options" 
              :key="idx"
              class="option-item"
              :class="{ selected: selectedOptions.includes(option.value) }"
              @click="toggleOption(option.value)"
            >
              <text>{{ option.label }}</text>
              <u-icon 
                v-if="selectedOptions.includes(option.value)" 
                name="checkbox-mark" 
                color="#2979ff" 
                size="20"
              ></u-icon>
            </view>
          </template>
          
          <!-- 类型3：价格区间 -->
          <template v-else-if="currentPrimary.type === 'range'">
            <view class="price-range">
              <u-input 
                v-model="priceMin" 
                placeholder="最低价" 
                type="number" 
                border="none"
                inputAlign="center"
              ></u-input>
              <text class="separator">-</text>
              <u-input 
                v-model="priceMax" 
                placeholder="最高价" 
                type="number" 
                border="none"
                inputAlign="center"
              ></u-input>
            </view>
          </template>
          
          <!-- 类型4：排序方式 -->
          <template v-else-if="currentPrimary.type === 'sort'">
            <view 
              v-for="(option, idx) in currentPrimary.options" 
              :key="idx"
              class="option-item"
              :class="{ selected: selectedSort === option.value }"
              @click="selectSort(option.value)"
            >
              <text>{{ option.label }}</text>
              <u-icon 
                v-if="selectedSort === option.value" 
                name="checkbox-mark" 
                color="#2979ff" 
                size="20"
              ></u-icon>
            </view>
          </template>
        </scroll-view>
        
        <!-- 底部操作按钮 -->
        <view class="secondary-footer">
          <u-button 
            v-if="currentPrimary.type === 'checkbox' || currentPrimary.type === 'range'"
            type="default" 
            size="medium" 
            @click="resetOptions"
          >
            重置
          </u-button>
          <u-button 
            type="primary" 
            size="medium" 
            @click="applyFilters"
          >
            确定
          </u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 筛选结果标签 -->
    <view v-if="appliedFilters.length > 0" class="filter-tags">
      <u-tag 
        v-for="(filter, idx) in appliedFilters" 
        :key="idx"
        :text="filter.label"
        type="primary"
        plain
        closeable
        @close="removeFilter(filter)"
        class="filter-tag"
      ></u-tag>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activePrimary: -1,
      showSecondary: false,
      currentPrimary: {},
      selectedOption: null,
      selectedOptions: [],
      selectedSort: 'default',
      priceMin: '',
      priceMax: '',
      appliedFilters: [],
      primaryFilters: [
        {
          name: '品牌',
          type: 'checkbox',
          key: 'brand',
          icon: 'arrow-down',
          options: [
            { label: '苹果', value: 'apple' },
            { label: '华为', value: 'huawei' },
            { label: '小米', value: 'xiaomi' },
            { label: 'OPPO', value: 'oppo' },
            { label: 'vivo', value: 'vivo' },
            { label: '三星', value: 'samsung' },
          ]
        },
        {
          name: '价格',
          type: 'range',
          key: 'price',
          icon: 'arrow-down',
        },
        {
          name: '分类',
          type: 'radio',
          key: 'category',
          icon: 'arrow-down',
          options: [
            { label: '手机', value: 'phone' },
            { label: '平板', value: 'tablet' },
            { label: '笔记本', value: 'laptop' },
            { label: '智能手表', value: 'watch' },
            { label: '耳机', value: 'earphone' },
          ]
        },
        {
          name: '排序',
          type: 'sort',
          key: 'sort',
          icon: 'arrow-down',
          options: [
            { label: '默认排序', value: 'default' },
            { label: '价格从低到高', value: 'price_asc' },
            { label: '价格从高到低', value: 'price_desc' },
            { label: '销量最高', value: 'sales' },
            { label: '评价最好', value: 'rating' },
          ]
        },
        {
          name: '服务',
          type: 'checkbox',
          key: 'service',
          icon: 'arrow-down',
          options: [
            { label: '7天无理由退换', value: 'return' },
            { label: '全国联保', value: 'warranty' },
            { label: '分期免息', value: 'installment' },
          ]
        }
      ]
    };
  },
  methods: {
    // 选择一级菜单
    selectPrimary(index) {
      this.activePrimary = index;
      this.currentPrimary = this.primaryFilters[index];
      this.showSecondary = true;
      
      // 初始化选项
      if (this.currentPrimary.type === 'radio') {
        this.selectedOption = this.getAppliedValue(this.currentPrimary.key) || null;
      } else if (this.currentPrimary.type === 'checkbox') {
        this.selectedOptions = this.getAppliedValue(this.currentPrimary.key) || [];
      } else if (this.currentPrimary.type === 'sort') {
        this.selectedSort = this.getAppliedValue(this.currentPrimary.key) || 'default';
      } else if (this.currentPrimary.type === 'range') {
        const priceRange = this.getAppliedValue('price') || {};
        this.priceMin = priceRange.min || '';
        this.priceMax = priceRange.max || '';
      }
    },
    
    // 关闭二级菜单
    closeSecondary() {
      this.showSecondary = false;
      this.activePrimary = -1;
    },
    
    // 选择单选选项
    selectOption(value) {
      this.selectedOption = value;
      this.applyFilters();
    },
    
    // 切换多选选项
    toggleOption(value) {
      if (this.selectedOptions.includes(value)) {
        this.selectedOptions = this.selectedOptions.filter(v => v !== value);
      } else {
        this.selectedOptions.push(value);
      }
    },
    
    // 选择排序方式
    selectSort(value) {
      this.selectedSort = value;
      this.applyFilters();
    },
    
    // 重置选项
    resetOptions() {
      if (this.currentPrimary.type === 'checkbox') {
        this.selectedOptions = [];
      } else if (this.currentPrimary.type === 'range') {
        this.priceMin = '';
        this.priceMax = '';
      }
    },
    
    // 应用筛选条件
    applyFilters() {
      const key = this.currentPrimary.key;
      
      // 移除旧的筛选条件
      this.appliedFilters = this.appliedFilters.filter(f => f.key !== key);
      
      // 添加新的筛选条件
      if (this.currentPrimary.type === 'radio' && this.selectedOption) {
        const option = this.currentPrimary.options.find(o => o.value === this.selectedOption);
        this.appliedFilters.push({
          key,
          value: this.selectedOption,
          label: `${this.currentPrimary.name}: ${option.label}`
        });
      } 
      else if (this.currentPrimary.type === 'checkbox' && this.selectedOptions.length > 0) {
        const labels = this.currentPrimary.options
          .filter(o => this.selectedOptions.includes(o.value))
          .map(o => o.label)
          .join(', ');
        this.appliedFilters.push({
          key,
          value: [...this.selectedOptions],
          label: `${this.currentPrimary.name}: ${labels}`
        });
      }
      else if (this.currentPrimary.type === 'sort') {
        const option = this.currentPrimary.options.find(o => o.value === this.selectedSort);
        this.appliedFilters.push({
          key,
          value: this.selectedSort,
          label: `排序: ${option.label}`
        });
      }
      else if (this.currentPrimary.type === 'range' && (this.priceMin || this.priceMax)) {
        const min = this.priceMin ? `¥${this.priceMin}` : '';
        const max = this.priceMax ? `¥${this.priceMax}` : '';
        const label = min && max ? `${min}-${max}` : min ? `${min}以上` : `${max}以下`;
        this.appliedFilters.push({
          key,
          value: { min: this.priceMin, max: this.priceMax },
          label: `价格: ${label}`
        });
      }
      
      // 关闭二级菜单
      this.closeSecondary();
      
      // 触发筛选事件
      this.$emit('filter-change', this.getFiltersObject());
    },
    
    // 移除筛选条件
    removeFilter(filter) {
      this.appliedFilters = this.appliedFilters.filter(f => f.key !== filter.key);
      this.$emit('filter-change', this.getFiltersObject());
    },
    
    // 获取已应用的筛选值
    getAppliedValue(key) {
      const filter = this.appliedFilters.find(f => f.key === key);
      return filter ? filter.value : null;
    },
    
    // 获取筛选对象
    getFiltersObject() {
      const filters = {};
      this.appliedFilters.forEach(filter => {
        filters[filter.key] = filter.value;
      });
      return filters;
    }
  }
};
</script>

<style lang="scss" scoped>
.filter-container {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.primary-filter {
  display: flex;
  white-space: nowrap;
  padding: 20rpx 0;
}

.primary-item {
  display: inline-flex;
  align-items: center;
  padding: 0 28rpx;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  position: relative;
  
  &.active {
    color: #2979ff;
    font-weight: bold;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 20rpx;
      right: 20rpx;
      height: 4rpx;
      background-color: #2979ff;
      border-radius: 2rpx;
    }
  }
  
  text {
    margin-right: 8rpx;
  }
}

.secondary-container {
  background-color: #ffffff;
  padding: 0 30rpx;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.secondary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.secondary-content {
  flex: 1;
  padding: 30rpx 0;
}

.option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;
  
  &.selected {
    color: #2979ff;
  }
}

.price-range {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  
  .u-input {
    flex: 1;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 20rpx;
    margin: 0 10rpx;
  }
  
  .separator {
    color: #999;
    padding: 0 20rpx;
  }
}

.secondary-footer {
  display: flex;
  padding: 20rpx 0 40rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .u-button {
    flex: 1;
    margin: 0 10rpx;
  }
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx;
  background-color: #f9f9f9;
}

.filter-tag {
  margin: 10rpx;
}
</style>